package com.jd.jstable.test.kv;

import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.serialize.ZkSerializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * User: wuxininfo
 */
@Component("zkClient")
public class ZkClientFactory implements FactoryBean<ZkClient>, DisposableBean {
    private static final Logger logger = LoggerFactory.getLogger(ZkClientFactory.class);
    private static final int DEFAULT_SESSION_TIMEOUT = 60000;
    private ZkClient zkClient;
    private int sessionTimeout;
    @Value("${zk.servers}")
    private String zkServers;
    private ZkSerializer zkSerializer;


    public ZkClientFactory(){
    }
    public void setSessionTimeout(int sessionTimeout) {
        this.sessionTimeout = sessionTimeout;
    }

    public void setZkServers(String zkServers) {
        this.zkServers = zkServers;
    }

    @Override
    public ZkClient getObject() throws Exception {
        if (sessionTimeout <= 0) {
            sessionTimeout = DEFAULT_SESSION_TIMEOUT;
        }
        if (zkSerializer == null) {
            zkSerializer = new StringSerializer();
        }
        zkClient = new ZkClient(zkServers, sessionTimeout, Integer.MAX_VALUE, zkSerializer);
        return zkClient;
    }

    @Override
    public Class<?> getObjectType() {
        return zkClient.getClass();
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void destroy() throws Exception {
        try {
            zkClient.close();
        } catch (Exception ex) {
            logger.error("destroy error!", ex);
        }
    }
}
